package com.kun.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.kun.config.EntityRedisSerializer;
import com.kun.entity.Book;
import com.kun.entity.BorrowRecord;
import com.kun.entity.User;
import com.kun.result.ExceptionMsg;
import com.kun.result.Response;
import com.kun.result.ResponseData;
import com.kun.service.BookService;
import com.kun.service.BorrowService;

/**
 * @description:
 * @author: KM
 * 2018年4月5日
 */
@Controller
@RequestMapping("/borrow")
public class BorrowController extends BaseController{
	
	@Autowired
	private BorrowService borrowService;
	
	@Autowired
	private BookService  bookServiceImpl;
	
	@Autowired
    protected RedisTemplate<String, Object> redisTemplate;
	
	@Autowired  
	DefaultKaptcha defaultKaptcha;
	
	
	@RequestMapping(value="") 
	public String getMyborrow(Model model){
		Subject  currentUser = SecurityUtils.getSubject(); 
		User user = (User) currentUser.getPrincipal();
		List<BorrowRecord> borrowList = new ArrayList<BorrowRecord>();
		if(user!=null){
			borrowList = borrowService.selectBorrowRecordByUserId(user.getId());
		}
		model.addAttribute("borrowList", borrowList);
		return "userBorrow";
	}
	
	@RequestMapping(value="/wechatBorrowPage") 
	public String wechatBorrowPage(Model model){
		Subject  currentUser = SecurityUtils.getSubject(); 
		User user = (User) currentUser.getPrincipal();
		List<BorrowRecord> borrowList = new ArrayList<BorrowRecord>();
		if(user!=null){
			borrowList = borrowService.selectBorrowRecordByUserId(user.getId());
		}
		model.addAttribute("borrowList", borrowList);
		return "wechatUserBorrow";
	}
	
	
	@RequestMapping(value="/toBorrow",method=RequestMethod.POST) 
	@ResponseBody
	public Response borrow(@RequestParam(name="bookId") int bookId,@RequestParam(name="amount") int amount){
		Subject  currentUser = SecurityUtils.getSubject(); 
		User user = (User) currentUser.getPrincipal();
		if(user!=null){
			int borrowNumber = borrowService.selectCurrnetBorrowNumByUserId(user.getId());
			if(currentUser.isPermitted("borrow:5")){
				if((borrowNumber + 1)>(user.getLevel() + 4)){
					Map<String,Integer> map = new HashMap<String,Integer>();
					map.put("currentBorrowNumber", borrowNumber);
					map.put("canBorrowNumber", user.getLevel() + 4);
					return new ResponseData(ExceptionMsg.UserBorrowLimit,map);
				}
			}else if(currentUser.isPermitted("borrow:3")){
				if((borrowNumber + 1)>3){
					Map<String,Integer> map = new HashMap<String,Integer>();
					map.put("currentBorrowNumber", borrowNumber);
					map.put("canBorrowNumber", 3);
					return new ResponseData(ExceptionMsg.UserBorrowLimit,map);
				}
			}else{
				return result(ExceptionMsg.UserNotHasBorrow);//无权限
			}
			
			if(amount<=0){
				return result(ExceptionMsg.FAILED);
			}
			Book book = bookServiceImpl.selectBookById(bookId);
			if(book==null){
				return result(ExceptionMsg.BookNotExit);//不存在该书
			}else if(amount>book.getBookamount()){//数量不足
				return new ResponseData(ExceptionMsg.AmountError,book.getBookamount());
			}
			
			BorrowRecord br = new BorrowRecord();
			Date d = new Date();
			String ordersNumber = "TS"; // 初始化订单编号
			DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
			String formatDate = format.format(d);
			int random = new Random().nextInt(100000);
			ordersNumber += formatDate + random;
			br.setBorrowId(ordersNumber);
			br.setUser(user);
			br.setUserId(user.getId());
			br.setBookId(bookId);
			br.setAmount(1);
			br.setBorrowTime(d);
			br.setIsDeal("0");
			Calendar c = Calendar.getInstance();
			c.setTime(d);
			c.add(Calendar.MONTH, 1);
			br.setReturnTime(c.getTime());
			String code = defaultKaptcha.createText();//生成 取书码code
			redisTemplate.setValueSerializer(new EntityRedisSerializer());
			redisTemplate.opsForValue().set(code, br, 60*60*24*3, TimeUnit.SECONDS);//3天过期
			int i =borrowService.insertBorrow(br);
			if(i!=0){
				//减库存  增加图书借阅记录数量
				bookServiceImpl.updateAmountByBookNumber(book.getBooknumber(), -amount,true);
				return new ResponseData(ExceptionMsg.SUCCESS,code);
			}else{
				redisTemplate.opsForValue().getOperations().delete(code);
				return result(ExceptionMsg.FAILED);
			}
		}else{
			return new ResponseData(ExceptionMsg.FAILED,"请重新登录！");
		}
	}

}
